﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using Microsoft.VisualStudio.Tools.Applications;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using System.IO;
using System.Windows.Forms;

namespace AddCustomizationCustomAction
{
    [RunInstaller(true)]
    public partial class AddCustomization : System.Configuration.Install.Installer
    {
        public AddCustomization()
      : base()
    {
      // Attach the 'Committed' event.
      this.Committed += new InstallEventHandler(MyInstaller_Committed);
      // Attach the 'Committing' event.
      //this.Committing += new InstallEventHandler(MyInstaller_Committing);

    }

        static readonly Guid SolutionID = new Guid("4fc997eb-e268-418a-b762-a02b7d679915");

        public override void Install(IDictionary stateSaver)
        {
            string[] nonpublicCachedDataMembers = null;

            Uri deploymentManifestLocation = null;
            if (Uri.TryCreate(
                Context.Parameters["deploymentManifestLocation"],
                UriKind.RelativeOrAbsolute,
                out deploymentManifestLocation) == false)
            {
                throw new InstallException(
                    "The location of the deployment manifest " +
                    "is missing or invalid.");
            }
            string documentLocation =
                Context.Parameters["documentLocation"];
            if (String.IsNullOrEmpty(documentLocation))
            {
                throw new InstallException(
                    "The location of the document is missing.");
            }
            string assemblyLocation =
                Context.Parameters["assemblyLocation"];
            if (String.IsNullOrEmpty(assemblyLocation))
            {
                throw new InstallException(
                    "The location of the assembly is missing.");
            }

            string targetLocation = CreateTargetLocation(documentLocation);
            // Check if FILE Exist & busy ...
            if (File.Exists(targetLocation))
            {
                int tryno = 3;
                while (FileInUse(targetLocation) & tryno > 0)
                {
                    DialogResult res = MessageBox.Show(string.Format("This file is in use : \"{0}\"\r\nPlease close first to continue the Installation !", targetLocation), "Cannot COPY file !");
                    if (res == DialogResult.OK) if (!FileInUse(targetLocation)) break;
                    tryno--;
                }
                if (tryno == 0) throw new Exception("Cannot COPY File !, File in Use Try 3 time already !");
            }

            // Copy Target File to Deliver Location
            File.Copy(documentLocation, targetLocation, true);
            if (ServerDocument.IsCustomized(targetLocation))
            {
                ServerDocument.RemoveCustomization(targetLocation);
            }
            ServerDocument.AddCustomization(
                targetLocation,
                assemblyLocation,
                SolutionID,
                deploymentManifestLocation,
                true,
                out nonpublicCachedDataMembers);
            stateSaver.Add("targetLocation", targetLocation);
            base.Install(stateSaver);
        }

        static bool FileInUse(string path)
        {
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                }
                return false;
            }
            catch (IOException ex)
            {
                return true;
            }
        }

        private void MyInstaller_Committed(object sender, InstallEventArgs e)
        {
            try
            {
                //Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
                //Process.Start(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\InstallExample.exe");
                string documentLocation =
                Context.Parameters["documentLocation"];
                if (String.IsNullOrEmpty(documentLocation))
                {
                    throw new InstallException(
                        "The location of the document is missing.");
                }

                string targetLocation = CreateTargetLocation(documentLocation);

                MessageBox.Show("New Farpac file is ready to use. You can \"SAVE AS\" or Copy this file from \"My Documents\" Folder");

                //System.Diagnostics.Process.Start(targetLocation);
            }
            catch
            {
                // Do nothing... 
            }
        }


        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);
        }

        public override void Rollback(IDictionary savedState)
        {
            base.Rollback(savedState);
        }

        public override void Uninstall(IDictionary savedState)
        {
            string targetLocation = (string)savedState["targetLocation"];
            if (String.IsNullOrEmpty(targetLocation) == false)
            {
                File.Delete(targetLocation);
            }
            base.Uninstall(savedState);
        }

        string CreateTargetLocation(string documentLocation)
        {
            string fileName = Path.GetFileName(documentLocation);
            string myDocuments = Environment.GetFolderPath(
                Environment.SpecialFolder.MyDocuments);
            return Path.Combine(myDocuments, fileName);
        }

    }
}
